package com.sunpy.permissionservice.login.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Slf4j
@Component
public class AuthorizeAccess implements AccessDecisionManager {

    @Value("${sys.login-uri}")
    private String loginUri;

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        log.info("+++++++++++++++++++++++AuthorizeAccess.decide");

        for (ConfigAttribute attribute : configAttributes) {
            // 如果用户第一次通过用户名和密码登录，直接让其通行
            if (loginUri.equals(attribute.getAttribute())) {
                return;
            }

            if ("UNAUTHORIZED".equals(attribute.getAttribute())) {
                throw new AccessDeniedException("该用户没有权限");
            }

            // 如果当前登录用户符合数据库的权限，放行
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(attribute.getAttribute())) {
                    return;
                }
            }
        }

        /**
         * 没有匹配的权限
         */
        throw new AccessDeniedException("该用户没有权限");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
